package com.hexiang.rocketmq.mq.producer.transaction;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 *
 */
@Slf4j
@Component
public class DemoSpringTransactionMQProducer {

    private String topic = "test_transaction_spring_topic";

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void sendMessageInTransaction(String msgBody) {
        try {
            //封装消息对象
            Message<String> message = MessageBuilder.withPayload(msgBody).setHeader("myMsgId", "123212312").build();
            //发送事务消息
            TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(topic, message, null);
            log.warn("transactionSendResult " + transactionSendResult.getMsgId());
        } catch (MessagingException e) {
            log.error("sendMessageInTransactionErr,msgBody ={}", msgBody, e);
        }
    }
}